package main

import (
	"crypto/tls"
	"flag"
	"io"
	"log"
	"net"
	"os"

	"gitee.com/jason_elva8325/socket-quickstart/protocol"
)

const (
	PO_MSG = "POMC000000000128.2314,123.34581"
	ST_MSG = "STMC0000000001.0101.000A"
)

var (
	listenHost  = flag.String("listen-host", "127.0.0.1", "TCP listen host")
	tcpPort     = flag.String("tcp-port", "3333", "TCP listen port")
	withSSL     = flag.Bool("with-ssl", false, "TCP with SSL")
	messageType = flag.String("message-type", "PO", "data message")
	logger      *log.Logger
)

func init() {
	// 全局日志对象定义
	logger = log.New(os.Stderr, "[message-client] ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
}

func main() {
	flag.Parse()

	var (
		conn net.Conn
		err  error
	)

	// 判断是否启用SSL
	if *withSSL {
		conn, err = tls.Dial("tcp", *listenHost+":"+*tcpPort, &tls.Config{
			InsecureSkipVerify: true,
		})
	} else {
		conn, err = net.Dial("tcp", *listenHost+":"+*tcpPort)
	}
	defer conn.Close()
	if err != nil {
		logger.Printf("Error connecting to %s.\n%s", conn.RemoteAddr().String(), err.Error())
	}
	logger.Printf("Connect to %s success.\n", conn.RemoteAddr().String())

	// 开始向服务器发送消息
	var message string
	switch *messageType {
	case "PO":
		message = PO_MSG
	case "ST":
		message = ST_MSG
	default:
		logger.Println("invalid message type")
		os.Exit(1)
	}
	packR := protocol.Pack([]byte(message))
	logger.Printf("pack string is: %s", packR)
	logger.Printf("pack hex is: %X", packR)
	// 可以在报文前后加入无效字符以混淆
	// packR = []byte("sdfs3432" + string(packR) + "  934kfj")
	// logger.Printf("append random chars string is: %s", packR)
	// logger.Printf("append random chars hex is: %X", packR)

	_, err = conn.Write(packR)
	if err != nil {
		logger.Printf("Error to send message because of %s", err.Error())
	}

	// 开始接收来自服务器的响应
	buffer := make([]byte, 2048)
	_, err = conn.Read(buffer)
	if err == io.EOF {
		logger.Printf("%s connection closed.", conn.RemoteAddr().String())
		os.Exit(1)
	} else if err != nil {
		logger.Printf("%s connection err:\n%s\n", conn.RemoteAddr().String(), err.Error())
		os.Exit(1)
	}
	// 解析请求数据报文
	logger.Printf("response is: %s", string(buffer))
}
